const DEF_POINT = '.'
const DEF_SYMBOL = ','
const DEF_RANGE = 3
const DEF_NULL = '--'
// -1234556.7898或 1378878 转成 -1,234,556.78 或 1,378,878
//  num 为 null 或 undefined 转成 DEF_NULL
export function formatterNumber(num: number | null | undefined) {
    const isNumber = judgeIsNumber(num)
    if (!isNumber) return DEF_NULL
    let resetNum = transformNum(num)
    const lastNum = formatterSymbol(resetNum)
    return lastNum
}
function transformNum(num: number | null | undefined): number {
    return Number(num)
}
// 判断是否数字(正数，负数，零，小数)
function judgeIsNumber(num: number | null | undefined) {
    const reg = /^-?[1-9]*(\.\d*)?$|^-?0(\.\d*)?$/
    if (reg.test(`${num}`)) return true
    return false
}

// 是否有小数点
function hasDecPoint(num: number) {
    return `${num}`.indexOf(DEF_POINT)
}
// 小数点后面数据，默认取两位
function getPointAfterNum(num: number, fixedNum: number = 2): number {
    const pontIndex = hasDecPoint(num)
    const startPointIndex = pontIndex + 1
    const endPointIndex = startPointIndex + fixedNum
    return pontIndex >= 0 ? +`${num}`.slice(startPointIndex, endPointIndex) : 0
}
// 是否是负数
function isNegativeNumber(num: number) {
    if (num < 0) return true
    return false
}
// 去掉小数点的正整数
function formatterDecPoint(num: number): number {
    const pontIndex = hasDecPoint(num)
    const notDecPointNum = pontIndex >= 0 ? +`${num}`.slice(0, pontIndex) : num
    return Math.abs(notDecPointNum)
}
// 添加逗号
function formatterSymbol(num: number) {
    const numList: Array<string> = splitNum(num)
    const tempList: Array<string> = []
    let count: number = 0
    for (let i = numList.length - 1; i >= 0; i--) {
        if (count === DEF_RANGE) {
            tempList.push(DEF_SYMBOL)
            count = 0
        } else {
            tempList.push(numList[i])
            count++
        }
    }
    const isMinusNum = isNegativeNumber(num)
    const symboNum = reverseAndJoinNum(tempList)
    const pointAfterNum = getPointAfterNum(num)
    const combinateNum = combinateFormattrNum(symboNum, pointAfterNum)
    return isMinusNum ? `-${combinateNum}` : combinateNum
}
// 切割num
function splitNum(num: number): Array<string> {
    return `${formatterDecPoint(num)}`.split('')
}
function reverseAndJoinNum(list: Array<number | string>): string {
    return list.reverse().join('')
}
// 组合数据
function combinateFormattrNum(symboNum: string, pointAfterNum: number) {
    if (pointAfterNum) return `${symboNum}.${pointAfterNum}`
    return symboNum
}
